<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="typeList" style="color: #333333" :header-cell-style="{background:'#E3E3E3'}">
      <el-table-column label="版本号" align="center" prop="version" :show-overflow-tooltip="true" />
      <el-table-column label="备注" align="center" prop="introduction" :show-overflow-tooltip="true" />

      <el-table-column label="是否最新" align="center" prop="latest" />
      <el-table-column label="文件大小" align="center" prop="size" :show-overflow-tooltip="true" />
      <el-table-column label="MD5" align="center" prop="md5" width="180" />
      <el-table-column label="路径" align="center" prop="path" width="180" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">

        <!--        <template slot-scope="scope">-->
        <!--          <span>{{ parseTime(scope.row.createTime) }}</span>-->
        <!--        </template>-->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button v-if="scope.row.latest===0" size="mini" type="text" icon="el-icon-edit" @click="setNews(scope.row)"
            v-hasPermi="['system:dict:edit']">设置为最新版本
          </el-button>
          <el-button v-else-if="scope.row.latest===1" size="mini" type="text" icon="el-icon-edit"
            @click="setOlds(scope.row)" v-hasPermi="['system:dict:edit']">取消新版本
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:dict:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
      @pagination="getList" />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-loading="uploadLoading" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入打包版本号" />
        </el-form-item>
        <el-form-item label="备注" prop="introduction">
          <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-upload style="display: flex;align-items: center" ref="upload" :file-list="uploadFileList"
          :auto-upload="false" action="#" :on-change="handleChange" :on-remove="handleRemove"
          :before-upload="uploadInspect">
          <el-button size="small" type="primary" icon="el-icon-upload">选择文件</el-button>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm1">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addApp,
    deleteById,
    listApp,
    setNew,
    setOld
  } from '@/api/system/app.js'
  import {
    parseTime
  } from '@/utils/ruoyi'
  import log from '@/views/monitor/job/log.vue'
  import axios from 'axios'
  import {
    Message
  } from 'element-ui'
  import { getToken } from '@/utils/auth'

  export default {
    name: 'App',
    data() {
      return {
        // 遮罩层
        loading: true,
        uploadLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 字典表格数据
        typeList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 状态数据字典
        statusOptions: [],
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          page: 1,
          size: 10
        },
        // 表单参数
        form: {},
        uploadFileList: [],
        // 表单校验
        rules: {
          version: [{
            required: true,
            message: '版本不能为空',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.getList()
      // this.getDicts("sys_normal_disable").then(response => {
      //   this.statusOptions = response.data;
      // });
    },
    methods: {

      parseTime,
      /** 查询列表 */
      getList() {
        this.loading = true
        listApp(this.queryParams).then(response => {
          console.log(response)
          this.typeList = response.content
          this.total = response.totalElements
          this.loading = false
        })
      },

      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      handleChange(files, fileList) {
        this.uploadFileList = fileList
        // this.number = fileList.length
      },
      handleRemove(files, fileList) {
        this.uploadFileList = fileList
        // this.number = fileList.length
      },
      uploadInspect(file) {
        let isRightSize = file.size / 1024 / 1024 <= 400
        if (!isRightSize) {
          this.$message.error('文件大小超过 400MB,请重新上传！')
        }
        return isRightSize
      },
      // 表单重置
      reset() {
        this.form = {}
        this.uploadFileList = []
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = []
        this.resetForm('queryForm')
        this.handleQuery()
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加字典类型'
      },
      /** 修改按钮操作 */
      setNews(row) {
        setNew(row.id).then(response => {
          if (response) {
            this.msgSuccess('设置成功');
            this.getList()
          } else {
            this.msgSuccess('设置失败只能有一个新版本');
          }
        })
      },
      setOlds(row) {
        setOld(row.id).then(response => {
          if (response) {
            this.msgSuccess('设置成功');
            this.getList()
          }
        })
      },
      submitForm1() {
        this.$refs['form'].validate(valid => {
          if (!valid) {
            return
          }
          if (this.uploadFileList.length < 1) {
            Message.closeAll()
            this.$message.error('文件不能为空')
            return
          }
        })
        console.log(this.uploadFileList)
        let formData = new FormData()
        let uploadFile = this.uploadFileList[0].raw
        // if (!uploadFile || uploadFile == )
        formData.append('file', uploadFile)
        this.uploadLoading = true
        axios({
          url: process.env.VUE_APP_BASE_API + '/ptAppVersion/app/upload',
          method: 'POST',
          headers: { 'Authorization': 'Bearer ' + getToken() },
          data: formData
        }).then(res => {
          console.log(res)
          this.form.size = uploadFile.size
          this.form.md5 = res.data.md5
          this.form.path = res.data.url
          this.submitForm()
        }).catch(err => {
          console.log(err)
          this.uploadLoading = false
          this.msgError('文件上传失败，请重试')
        })

      },
      /** 提交按钮 */
      submitForm: function() {
        addApp(this.form).then(response => {
          this.msgSuccess("上传成功");
          console.log(response)
          this.uploadLoading = false
          this.open = false
          this.getList()
        })
        this.uploadLoading = false
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const id = row.id || this.ids
        this.$confirm('是否确认删除所选数据?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          type: 'warning'
        }).then(function() {
          return deleteById(id)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      },
    },

  }
</script>
